<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';

import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';

import { AuthenticationLogin, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { changePasswordApi } from '#/api/core/auth';
import { notification } from 'ant-design-vue';
import { useAuthStore } from '#/store';

defineOptions({ name: 'ChangePassword' });

const route = useRoute();
const loading = ref(false);
const authStore = useAuthStore();

// 从路由参数获取用户名（首次登录时传递的）
const username = computed(() => route.query.username as string);

const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: $t('user.firstLogin.changePassword.oldPassword.placeholder'),
      },
      fieldName: 'oldPassword',
      label: $t('user.firstLogin.changePassword.oldPassword.label'),
      rules: z.string().min(1, { message: $t('user.firstLogin.changePassword.oldPassword.required') }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: $t('user.firstLogin.changePassword.newPassword.placeholder'),
      },
      fieldName: 'newPassword',
      label: $t('user.firstLogin.changePassword.newPassword.label'),
      rules: z.string()
        .min(1, { message: $t('user.firstLogin.changePassword.newPassword.required') })
        .min(8, { message: $t('user.firstLogin.changePassword.newPassword.minLength') })
        .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>])/, {
          message: $t('user.firstLogin.changePassword.newPassword.format'),
        }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: $t('user.firstLogin.changePassword.confirmPassword.placeholder'),
      },
      fieldName: 'confirmPassword',
      label: $t('user.firstLogin.changePassword.confirmPassword.label'),
      rules: z.string()
        .min(1, { message: $t('user.firstLogin.changePassword.confirmPassword.required') })
        .refine((value: string) => {
          // 这里暂时简化验证，实际项目中可以通过其他方式获取新密码值
          return true;
        }, { message: $t('user.firstLogin.changePassword.confirmPassword.notMatch') }),
    },
  ];
});

const handleSubmit = async (values: any) => {
  try {
    loading.value = true;

    // 检查用户名是否存在
    if (!username.value) {
      notification.error({
        message: $t('user.firstLogin.changePassword.failed'),
        description: '用户名信息缺失，请重新登录',
        duration: 3,
      });
      return;
    }

    const result = await changePasswordApi({
      username: username.value,
      password: values.oldPassword,
      realName: values.newPassword,
      email: values.confirmPassword,
    });

    // 检查响应是否有效
    if (!result) {
      // 如果响应为null，可能是成功的情况
      notification.success({
        message: $t('user.firstLogin.changePassword.success'),
        description: '密码修改成功',
        duration: 3,
      });

      // 密码修改成功，清除登录状态并跳转到登录页重新登录
      await authStore.logout(false);
      return;
    }

    // 根据后端返回的success字段判断是否成功
    if (result.success) {
      notification.success({
        message: $t('user.firstLogin.changePassword.success'),
        description: result.message,
        duration: 3,
      });

      // 密码修改成功，清除登录状态并跳转到登录页重新登录
      await authStore.logout(false);
    } else {
      notification.error({
        message: $t('user.firstLogin.changePassword.failed'),
        description: result.message,
        duration: 3,
      });
    }
    } catch (error: any) {
    console.error('🔍 密码修改失败:', error);
    console.error('🔍 错误详情:', {
      message: error?.message,
      response: error?.response,
      status: error?.response?.status,
      data: error?.response?.data
    });

    // 提取错误信息，不显示data中的信息
    let errorMessage = $t('common.submit.failed');
    if (error?.message) {
      // 如果错误信息包含冒号，只取冒号前的部分
      const messageParts = error.message.split(':');
      errorMessage = messageParts[0] || $t('common.submit.failed');
    }

    notification.error({
      message: $t('user.firstLogin.changePassword.failed'),
      description: errorMessage,
      duration: 3,
    });
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="flex-col-center dark:bg-background-deep bg-background relative px-6 py-10 lg:flex-initial lg:px-8">
    <div class="enter-x mt-6 w-full sm:mx-auto md:max-w-md">
      <!-- 标题部分 -->
      <div class="text-center mb-8">
        <h2 class="text-2xl font-semibold text-foreground mb-2">
          {{ $t('user.firstLogin.changePassword.title') }}
        </h2>
        <p class="text-muted-foreground text-sm">
          {{ $t('user.firstLogin.changePassword.description') }}
        </p>
      </div>

      <!-- 表单部分 -->
      <AuthenticationLogin
        :form-schema="formSchema"
        :loading="loading"
        @submit="handleSubmit"
      />

      <!-- 密码要求部分 -->
      <div class="mt-6 p-4 bg-muted/50 rounded-lg">
        <h4 class="text-sm font-medium text-foreground mb-3">
          {{ $t('user.firstLogin.changePassword.requirements.title') }}
        </h4>
        <ul class="text-xs text-muted-foreground space-y-1">
          <li>{{ $t('user.firstLogin.changePassword.requirements.length') }}</li>
          <li>{{ $t('user.firstLogin.changePassword.requirements.uppercase') }}</li>
          <li>{{ $t('user.firstLogin.changePassword.requirements.lowercase') }}</li>
          <li>{{ $t('user.firstLogin.changePassword.requirements.number') }}</li>
          <li>{{ $t('user.firstLogin.changePassword.requirements.special') }}</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 使用主题适配的样式，无需额外的CSS */
</style>
